﻿using Prism.Commands;
using Prism.Mvvm;
using StockTools.Configuration;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Linq;
using Sharp.Infrastructure.Network;
using System.Net;

namespace StockTools.ViewModel
{
    public class StockMonitorViewModel : BindableBase
    {
        private ObservableCollection<SettingConfig.StockItem> stockData;
        private string code;

        public StockMonitorViewModel()
        {
            this.StockData = new ObservableCollection<SettingConfig.StockItem>();

            AddCommand = new DelegateCommand(ExecuteAddCommand);
            DelCommand = new DelegateCommand(ExecuteDelCommand);
            LoadSettingConfig();
        }
        public string Code { get => code; set => SetProperty(ref code, value); }
        public ObservableCollection<SettingConfig.StockItem> StockData { get => stockData; set => SetProperty(ref stockData, value); }

        internal void Refurbish()
        {
            updateStockinfo(this.StockData.Select(x => x.Key).ToArray());
        }

        public DelegateCommand AddCommand { get; set; }
        public DelegateCommand DelCommand { get; set; }
        private void LoadSettingConfig()
        {
            var settingConfig = SystemConfigManage.Read<SettingConfig>();

            this.StockData.AddRange(settingConfig.StockData.ToArray());

        }

        void ExecuteAddCommand()
        {
            StockData.Add(new SettingConfig.StockItem()
            {
                Key = this.Code,
                Name = ""
            });
            var settingConfig = new SettingConfig();

            settingConfig.Save("", null, StockData);

            updateStockinfo(this.Code);
        }
        void ExecuteDelCommand()
        {
            var delData = StockData.Where(x => x.IsActive).ToList();
            delData.ForEach(x =>
            {
                StockData.Remove(x);
            });
            var settingConfig = new SettingConfig();

            settingConfig.Save(this.Code, null, StockData);
        }

        private void updateStockinfo(params string[] codes)
        {
            if (codes == null || codes.Length == 0) return;

            List<string> output = new List<string>();
            codes.ToList().ForEach((item) =>
           {
               if (item.IsNullOrEmpty()) return;
               output.Add((item.StartsWith("6") ? "sh" : "sz") + item);
           });
            var url = "http://qt.gtimg.cn/q=" + string.Join(',', output.ToArray());
            var net = new NetHelper();

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var res = net.Get(url);
            if (res.StatusCode == HttpStatusCode.OK)
            {
                var data = res.Html.Split(";", StringSplitOptions.RemoveEmptyEntries).ToList();
                this.StockData.ToList().ForEach(item =>
                {
                    if (item.Key.IsNullOrEmpty()) return;

                    var row = data.Where(x => x.Contains(item.Key)).FirstOrDefault();
                    if (row.IsNullOrEmpty()) return;

                    var col = row.Split('~').Skip(0).ToArray();
                    item.Name = col[1];
                    item.LatestPrice = decimal.Parse(col[3]);
                    item.Highest = decimal.Parse(col[33]);
                    item.Lowest = decimal.Parse(col[34]);
                    item.Rate = decimal.Parse(col[32])/100;
                });
            }
        }
    }
}